package com.yanchangapp.ui.activity.base;

import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.zxl.baselib.baseapp.AppManager;
import com.zxl.baselib.bean.response.BaseResponse;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.ui.base.BaseObserver;
import com.zxl.baselib.ui.base.BasePresenter;
import com.zxl.baselib.ui.base.ExceptionHandle;
import com.zxl.baselib.util.CheckUtils;
import com.yanchangapp.R;
import com.yanchangapp.base.ApiRetrofit;
import com.yanchangapp.commom.AppConstant;
import com.yanchangapp.model.cache.UserCache;
import com.yanchangapp.ui.activity.BaseTimeTask;
import com.yanchangapp.ui.activity.BaseTimeTaskListener;
import com.zxl.baselib.util.Md5Utils;
import com.zxl.baselib.util.NetUtils;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.util.window.KeyboardHelper;

import java.util.Timer;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 找回密码界面
 */
public class ForgetPwdActivity extends BaseActivity implements BaseTimeTaskListener {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.etPhone)
    EditText etPhone;
    @BindView(R.id.etCode)
    EditText etCode;
    @BindView(R.id.btnSendSms)
    Button btnSendSms;
    @BindView(R.id.etNewPassword)
    EditText etNewPassword;
    @BindView(R.id.ivSeePwd)
    ImageView ivSeePwd;
    @BindView(R.id.etPasswordSure)
    EditText etPasswordSure;
    @BindView(R.id.ivSeePwdSure)
    ImageView ivSeePwdSure;
    @BindView(R.id.btnLogin)
    Button btnLogin;
    private Timer mTimer;
    private int mCount;
    @Override
    protected void init() {

    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_forget_pwd;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvToolbarTitle.setText("找回密码");
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void onDestroy() {
        if (mTimer != null){
            mTimer.cancel();
            mTimer = null;
        }
        super.onDestroy();
    }

    @OnClick({R.id.ivToolbarNavigation, R.id.btnSendSms, R.id.btnLogin,R.id.ivSeePwd,R.id.ivSeePwdSure})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivToolbarNavigation:
                finish();
                break;
            case R.id.btnSendSms:
                sendSms();
                break;
            case R.id.btnLogin:
                KeyboardHelper.hideKeyboard(btnLogin);
                netForgetPwd();
                break;
            case R.id.ivSeePwd:
                actionChangeSee();
                break;
            case R.id.ivSeePwdSure:
                actionSureSee();
                break;
        }
    }

    /*
     * 密码点击事件(眼睛)
     */
    public void actionChangeSee() {
        if (etNewPassword.getTransformationMethod() == HideReturnsTransformationMethod.getInstance()) {
            // 由可见变为不可见
            etNewPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            ivSeePwd.setImageResource(R.mipmap.hide_pwd);
        } else {
            // 由不可见变为可见
            etNewPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            ivSeePwd.setImageResource(R.mipmap.show_pwd);
        }
    }

    /*
     * 确定密码点击事件(眼睛)
     */
    public void actionSureSee() {
        if (etPasswordSure.getTransformationMethod() == HideReturnsTransformationMethod.getInstance()) {
            // 由可见变为不可见
            etPasswordSure.setTransformationMethod(PasswordTransformationMethod.getInstance());
            ivSeePwdSure.setImageResource(R.mipmap.hide_pwd);
        } else {
            // 由不可见变为可见
            etPasswordSure.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            ivSeePwdSure.setImageResource(R.mipmap.show_pwd);
        }
    }

    private void sendSms(){
        String mobile = etPhone.getText().toString();
        if (TextUtils.isEmpty(mobile)){
            UIUtils.showToast("请输入手机号码");
            return;
        }
        if (!CheckUtils.isMobile(mobile)){
            UIUtils.showToast("手机号格式错误");
            return;
        }
        if (!NetUtils.isConnectedAndToast(this)){
            return;
        }
        netQuerySms(mobile);
        initTimer();
    }

    public void netQuerySms(String mobile){
        ApiRetrofit.getInstance().getSms(mobile)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onNext(BaseResponse baseResponse) {
                        if (baseResponse.getCode() == AppConstant.REQUEST_SUCCESS ||
                                baseResponse.getCode() == 203){
                            UIUtils.showToast("短信发送成功");
                        }else {
                            reBackTimeTask();
                            UIUtils.showToast(baseResponse.getMsg());
                        }
                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseException exception) {
                        reBackTimeTask();
                    }
                });
    }

    private void initTimer(){
        mCount = 60;
        // 设置发送按钮不可点击
        btnSendSms.setEnabled(false);
        if (mTimer == null){
            mTimer = new Timer();
        }
        mTimer.schedule(new BaseTimeTask(this),0,1000);
    }

    @Override
    public void doTimeTask() {
        runOnUiThread(() -> {
            if (mCount > 0){
                btnSendSms.setText(String.valueOf(mCount));
                mCount --;
            }else {
                mTimer.cancel();
                btnSendSms.setText("获取验证码");
                // 设置发送按钮可以点击...
                btnSendSms.setEnabled(true);
                mTimer = null;
            }
        });
    }

    public void reBackTimeTask(){
        mTimer.cancel();
        mTimer = null;
        btnSendSms.setText("获取验证码");
        // 设置发送按钮可以点击...
        btnSendSms.setEnabled(true);
    }

    public void netForgetPwd(){
        String mobile = etPhone.getText().toString();
        if (TextUtils.isEmpty(mobile)){
            UIUtils.showToast("请输入手机号码");
            return;
        }
        if (!CheckUtils.isMobile(mobile)){
            UIUtils.showToast("手机号格式错误");
            return;
        }

        String smsCode = etCode.getText().toString();
        if (TextUtils.isEmpty(smsCode)){
            UIUtils.showToast("请输入验证码");
            return;
        }

        String password = etNewPassword.getText().toString();
        if (TextUtils.isEmpty(password)){
            UIUtils.showToast("密码不能为空");
            return;
        }

        if (!CheckUtils.isPassword(password)){
            UIUtils.showToast("新密码必须为6-16位数字或字母组合");
            return;
        }

        String newPassword = etPasswordSure.getText().toString();
        if (TextUtils.isEmpty(newPassword)){
            UIUtils.showToast("确认密码不能为空");
            return;
        }

        if (!CheckUtils.isPassword(newPassword)){
            UIUtils.showToast("确认密码必须为6-16位数字或字母组合");
            return;
        }

        if (!password.equals(newPassword)){
            UIUtils.showToast("您输入的密码不一致");
            return;
        }

        if (!NetUtils.isConnectedAndToast(this)){
            return;
        }

        ApiRetrofit.getInstance().forgetPassword(Md5Utils.md5(password),mobile,smsCode)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onNext(BaseResponse baseResponse) {
                        if (baseResponse.getCode() == AppConstant.REQUEST_SUCCESS){
                            UIUtils.showToast("找回密码成功");
                            forgetSuccess();
                        }else {
                            UIUtils.showToast(baseResponse.getMsg());
                        }
                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseException exception) {
                        UIUtils.showToast(exception.message);
                    }
                });
    }

    public void forgetSuccess(){
        if (getIntent().hasExtra(AppConstant.EXTRA_ORIFIN_LOGIN)){
            finish();
        }else {
            doLogout();
        }
    }

    public void doLogout(){
        Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
            UserCache.clear();
            emitter.onNext(true);
            emitter.onComplete();
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Boolean>() {
                    @Override
                    public void onNext(Boolean aBoolean) {
                        AppManager.getAppManager().finishAllActivity();
                        jumpToActivityAndClearTask(LoginActivity.class);
                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseException exception) {

                    }
                });
    }
}
